package com.lv.service.dialog

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.util.component1
import androidx.core.util.component2
import com.github.gzuliyujiang.wheelpicker.widget.LinkageWheelLayout
import com.lv.common.imp.OnPositionMore
import com.lv.common.utils.TimeUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.widget.linkbar.ZFlowLayout
import com.lv.service.R
import com.lv.service.bean.CommonSelectedBean
import com.lv.service.room.category.CategoryBean
import com.lv.service.utils.YgxToolsKt
import com.lv.service.weidget.picker.ThirdLikeProvider
import com.lxj.xpopup.core.BottomPopupView

/**
 * 作者： ygx
 * 创建日期：2022/10/10 10:32 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class Time2StepPopupView(
    private val mContext: Context,
    private var intWheel: Int = 0,//显示第几个 -1 全部显示
    private val mTitle: String,
    private val mAllBeans: List<CategoryBean>?,
    private val mAllCusBeans: List<CategoryBean>?,
    private val mOpenBeans: List<CommonSelectedBean>? = null,
    private var currentTopProvin: Int = -1,
    private var mWheelPosition1: Int = 0,
    private var mWheelPosition2: Int = 0,
    private var mWheelPosition3: Int = 0,
    private var mWheelStartPosition1: Int = 0,
    private var mWheelStartPosition2: Int = 0,
    private var mWheelStartPosition3: Int = 0,
    private var mWheelEndPosition1: Int = 0,
    private var mWheelEndPosition2: Int = 0,
    private var mWheelEndPosition3: Int = 0,
    private var mStartTime: String = "",
    private var mEndTime: String = "",
    private var mWheelPos: Int? = 0,
    private val positionListener: OnPositionMore<String>? = null
) :
    BottomPopupView(mContext), OnClickListener {
    private var tvTitle: TextView? = null
    private var tvTitleCustom: TextView? = null
    private var tvStart: TextView? = null
    private var tvEnd: TextView? = null
    private var tvSure: TextView? = null
    private var mFlowLayout: ZFlowLayout? = null
    private var wheelLinkage: LinkageWheelLayout? = null
    private var wheelLinkageCus: LinkageWheelLayout? = null
    private var clContainerTop: ConstraintLayout? = null
    private var ivClose: ImageView? = null
    private var tvLine1: View? = null
    private var tvLine2: View? = null
    private var viewStartLine: View? = null
    private var viewEndLine: View? = null
    private var viewTop: View? = null
    private var timeCurrent: Int = 0

    private val mViewList = mutableListOf<View>()

    override fun getImplLayoutId(): Int {
        return R.layout.time_2step_popup
    }

    override fun onCreate() {
        super.onCreate()
        viewTop = findViewById<View>(R.id.view_top)
        tvTitle = findViewById<TextView>(R.id.tv_title)
        tvTitleCustom = findViewById<TextView>(R.id.tv_title_custom)
        tvStart = findViewById<TextView>(R.id.tv_start)
        tvEnd = findViewById<TextView>(R.id.tv_end)
        tvSure = findViewById<TextView>(R.id.tv_sure)
        mFlowLayout = findViewById<ZFlowLayout>(R.id.z_flow)
        wheelLinkage = findViewById<LinkageWheelLayout>(R.id.wheel_linkage)
        wheelLinkageCus = findViewById<LinkageWheelLayout>(R.id.wheel_linkage_cus)
        clContainerTop = findViewById<ConstraintLayout>(R.id.cl_container_top)
        ivClose = findViewById<ImageView>(R.id.iv_close)
        tvLine1 = findViewById<View>(R.id.tv_line1)
        tvLine2 = findViewById<View>(R.id.tv_line2)
        viewStartLine = findViewById<View>(R.id.view_start_line)
        viewEndLine = findViewById<View>(R.id.view_end_line)
        viewTop?.setOnClickListener(this)
        tvTitle?.setOnClickListener(this)
        tvTitleCustom?.setOnClickListener(this)
        tvSure?.setOnClickListener(this)
        ivClose?.setOnClickListener(this)
        tvStart?.setOnClickListener(this)
        tvEnd?.setOnClickListener(this)
        initView()
        initEvnet()
        setFlowData()
    }

    private fun initView() {
        tvTitle?.text = mTitle

        val thirdLikeProvider = ThirdLikeProvider(mAllBeans)
        wheelLinkage?.setData(thirdLikeProvider)
        val thirdLikeCusProvider = ThirdLikeProvider(mAllCusBeans)
        wheelLinkageCus?.setData(thirdLikeCusProvider)

        wheelLinkage?.setDefaultValue(mWheelPosition1, mWheelPosition2, mWheelPosition3)
        wheelLinkageCus?.setDefaultValue(
            mWheelStartPosition1,
            mWheelStartPosition2,
            mWheelStartPosition3
        )

        when(intWheel){
            0->{
                wheelLinkage?.firstWheelView?.visibility = View.VISIBLE
                wheelLinkage?.secondWheelView?.visibility = View.GONE
                wheelLinkage?.thirdWheelView?.visibility = View.GONE
            }
            1->{
                wheelLinkage?.firstWheelView?.visibility = View.VISIBLE
                wheelLinkage?.secondWheelView?.visibility = View.VISIBLE
                wheelLinkage?.thirdWheelView?.visibility = View.GONE
            }
            2->{
                wheelLinkage?.firstWheelView?.visibility = View.VISIBLE
                wheelLinkage?.secondWheelView?.visibility = View.VISIBLE
                wheelLinkage?.thirdWheelView?.visibility = View.VISIBLE
            }

        }
        wheelLinkageCus?.firstWheelView?.visibility = View.VISIBLE
        wheelLinkageCus?.secondWheelView?.visibility = View.VISIBLE
        wheelLinkageCus?.thirdWheelView?.visibility = View.VISIBLE

        initUI(mWheelPos)
        initCustomTime()
    }

    private fun initUI(positonType: Int?) {
        when (positonType) {
            0 -> {
                wheelLinkage?.visibility = View.VISIBLE
                tvLine1?.visibility = View.VISIBLE
                wheelLinkageCus?.visibility = View.GONE
                clContainerTop?.visibility = View.GONE
                tvLine2?.visibility = View.GONE
            }

            else -> {
                wheelLinkage?.visibility = View.GONE
                tvLine1?.visibility = View.GONE
                wheelLinkageCus?.visibility = View.VISIBLE
                clContainerTop?.visibility = View.VISIBLE
                tvLine2?.visibility = View.VISIBLE
            }

        }
    }

    private fun initCustomTime() {
        when (timeCurrent) {
            0 -> {
                if (mStartTime.isEmpty()) {
                    mWheelStartPosition1 = (mAllCusBeans?.size ?: 0) - 1
                    mWheelStartPosition2 =
                        (mAllCusBeans?.get(mWheelStartPosition1)?.telSecondCategories?.size
                            ?: 0) - 1
                    mWheelStartPosition3 =
                        (mAllCusBeans?.get(mWheelStartPosition1)?.telSecondCategories?.get(
                            mWheelStartPosition2
                        )?.telThirdCategories?.size ?: 0) - 1
                    mStartTime = "${mAllCusBeans?.get(mWheelStartPosition1)?.name}-${
                        mAllCusBeans?.get(mWheelStartPosition1)?.telSecondCategories?.get(
                            mWheelStartPosition2
                        )?.name
                    }-${
                        mAllCusBeans?.get(mWheelStartPosition1)?.telSecondCategories?.get(
                            mWheelStartPosition2
                        )?.telThirdCategories?.get(mWheelStartPosition3)?.name
                    }"
                } else {
                    initStartScanTimePicker()
                }
                wheelLinkageCus?.setDefaultValue(
                    mWheelStartPosition1,
                    mWheelStartPosition2,
                    mWheelStartPosition3
                )
                tvStart?.text = mStartTime
                tvEnd?.text = mEndTime
                tvStart?.setTextColor(Color.parseColor("#eb613d"))
                viewStartLine?.setBackgroundResource(com.lv.common.R.drawable.bg_theme_2)
                tvEnd?.setTextColor(Color.parseColor("#242424"))
                viewEndLine?.setBackgroundResource(com.lv.common.R.drawable.bg_24_2)
            }
            1 -> {
                if (mEndTime.isEmpty()) {
                    mWheelEndPosition1 = (mAllCusBeans?.size ?: 0) - 1
                    mWheelEndPosition2 =
                        (mAllCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.size ?: 0) - 1
                    mWheelEndPosition3 =
                        (mAllCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.get(
                            mWheelEndPosition2
                        )?.telThirdCategories?.size ?: 0) - 1
                    mEndTime = "${mAllCusBeans?.get(mWheelEndPosition1)?.name}-${
                        mAllCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.get(
                            mWheelEndPosition2
                        )?.name
                    }-${
                        mAllCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.get(
                            mWheelEndPosition2
                        )?.telThirdCategories?.get(mWheelEndPosition3)?.name
                    }"
                } else {
                    initEndScanTimePicker()
                }
                wheelLinkageCus?.setDefaultValue(
                    mWheelEndPosition1,
                    mWheelEndPosition2,
                    mWheelEndPosition3
                )
                tvStart?.text = mStartTime
                tvEnd?.text = mEndTime
                tvStart?.setTextColor(Color.parseColor("#242424"))
                viewStartLine?.setBackgroundResource(com.lv.common.R.drawable.bg_24_2)
                tvEnd?.setTextColor(Color.parseColor("#eb613d"))
                viewEndLine?.setBackgroundResource(com.lv.common.R.drawable.bg_theme_2)
            }
        }
    }

    private fun initStartScanTimePicker() {
        val list = mutableListOf<CategoryBean>()
        mAllCusBeans?.let { list.addAll(it) }
        val newData = TimeUtil.getNowDateTime("yyyy-MM-dd")
        if (mStartTime.isEmpty()) {
            mStartTime = newData
        }
        val startSplit = mStartTime.split("-")
        val (x, y, z) = YgxToolsKt.initThirdAddressInt(
            list,
            startSplit[0],
            String.format("%02d", startSplit[1].toDouble().toInt()),
            String.format("%02d", startSplit[2].toDouble().toInt())
        )
        mWheelStartPosition1 = x
        mWheelStartPosition2 = y
        mWheelStartPosition3 = z
    }

    private fun initEndScanTimePicker() {
        val list = mutableListOf<CategoryBean>()
        val newData = TimeUtil.getNowDateTime("yyyy-MM-dd")
        mAllCusBeans?.let { list.addAll(it) }
        if (mEndTime.isEmpty()) {
            mEndTime = newData
        }
        val endSplit = mEndTime.split("-")
        val (a, b, c) = YgxToolsKt.initThirdAddressInt(
            list,
            endSplit[0],
            String.format("%02d", endSplit[1].toDouble().toInt()),
            String.format("%02d", endSplit[2].toDouble().toInt())
        )
        val eary = YgxUtilsKt.compareDates(mEndTime, newData)
        mWheelEndPosition1 = a
        mWheelEndPosition2 = b
        if (eary == -1 || eary == 0) {
            mWheelEndPosition3 = c
        } else {
            val days = String.format("%02d", newData.split("-")[2].toDouble().toInt())
            mEndTime =
                "${endSplit[0]}-${String.format("%02d", endSplit[1].toDouble().toInt())}-$days"
            mWheelEndPosition3 =
                (mAllCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.get(mWheelEndPosition2)?.telThirdCategories?.size
                    ?: 1) - 1
            tvEnd?.text = mEndTime
        }
    }

    private fun initEvnet() {
        wheelLinkage?.setOnLinkageSelectedListener { first, second, third ->
            mWheelPosition1 = wheelLinkage?.firstWheelView?.currentPosition ?: 0
            mWheelPosition2 = wheelLinkage?.secondWheelView?.currentPosition ?: 0
            mWheelPosition3 = wheelLinkage?.thirdWheelView?.currentPosition ?: 0
//            mBinding.tvSearchCategory.text =
//                "${mAllBeans!![mWheelPosition1].name}-${mAllBeans[mWheelPosition1].telSecondCategories!![mWheelPosition2].name}"
        }
        wheelLinkageCus?.setOnLinkageSelectedListener { first, second, third ->
            val position1 = wheelLinkageCus?.firstWheelView?.currentPosition ?: 0
            val position2 = wheelLinkageCus?.secondWheelView?.currentPosition ?: 0
            val position3 = wheelLinkageCus?.thirdWheelView?.currentPosition ?: 0
            val time = "${mAllCusBeans?.get(position1)?.name}-${
                mAllCusBeans?.get(position1)?.telSecondCategories?.get(
                    position2
                )?.name
            }-${
                mAllCusBeans?.get(position1)?.telSecondCategories?.get(
                    position2
                )?.telThirdCategories?.get(position3)?.name
            }"
            when (timeCurrent) {
                0 -> {
                    mWheelStartPosition1 = position1
                    mWheelStartPosition2 = position2
                    mWheelStartPosition3 = position3
                    mStartTime = time
                    tvStart?.text = mStartTime
                }
                1 -> {
                    mWheelEndPosition1 = position1
                    mWheelEndPosition2 = position2
                    mWheelEndPosition3 = position3
                    mEndTime = time
                    tvEnd?.text = mEndTime
                }
            }
            mViewList.forEach { viewItem ->
                viewItem.setBackgroundResource(com.lv.common.R.drawable.bg_f9_15)
            }
            mOpenBeans?.forEach { viewItem ->
                viewItem.selected = false
            }
            currentTopProvin = -1
//            mBinding.tvSearchCategory.text =
//                "${mAllBeans!![mWheelPosition1].name}-${mAllBeans[mWheelPosition1].telSecondCategories!![mWheelPosition2].name}"
        }

    }

    private fun setFlowData() {
        mViewList.clear()
        if (!mOpenBeans.isNullOrEmpty()) {
            for (i in 0 until mOpenBeans.size) {
                val textChild = LayoutInflater.from(mContext)
                    .inflate(
                        R.layout.text_tag_layout_gray,
                        mFlowLayout, false
                    ) as TextView
                textChild.text = mOpenBeans[i].name
                mViewList.add(textChild)
            }
            if (currentTopProvin != -1) {
                mViewList[currentTopProvin].setBackgroundResource(com.lv.common.R.drawable.bg_tab_eb613d_14)
            }

            mFlowLayout?.setChildren(mViewList)
            mFlowLayout?.setOnTagClickListener { view, position ->
                mViewList.forEach { viewItem ->
                    viewItem.setBackgroundResource(com.lv.common.R.drawable.bg_f9_15)
                }
                mOpenBeans.forEach { viewItem ->
                    viewItem.selected = false
                }
                currentTopProvin = position
                mOpenBeans[position].selected = true
                mViewList[position].setBackgroundResource(com.lv.common.R.drawable.bg_tab_eb613d_14)
                mWheelEndPosition1 = (mAllCusBeans?.size ?: 0) - 1
                mWheelEndPosition2 =
                    (mAllCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.size ?: 0) - 1
                mWheelEndPosition3 =
                    (mAllCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.get(
                        mWheelEndPosition2
                    )?.telThirdCategories?.size ?: 0) - 1
                val yearString = mAllCusBeans?.get(mWheelEndPosition1)?.name ?: "2024"
                val monthString = mAllCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.get(
                    mWheelEndPosition2
                )?.name ?: "12"
                val dayString = mAllCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.get(
                    mWheelEndPosition2
                )?.telThirdCategories?.get(mWheelEndPosition3)?.name ?: "1"
                mEndTime = "${yearString}-${monthString}-${dayString}"
                val subM = mOpenBeans[position].postiont
//                when (position) {
//                    0 -> {//近三个月
//                        subM = 3
//                    }
//                    1 -> {//近半年
//                        subM = 6
//                    }
//                    2 -> {//近1年
//                        subM = 12
//                    }
//                }
                val (a, b) = TimeUtil.getPreData(
                    yearString.toDouble().toInt(),
                    monthString.toDouble().toInt(),
                    subM
                )
                val list = mutableListOf<CategoryBean>()
                mAllCusBeans?.let { list.addAll(it) }
                val (x, y, z) = YgxToolsKt.initThirdAddressInt(
                    list, "$a", String.format("%02d", b),
                    String.format("%02d", dayString.toDouble().toInt())
                )
                mWheelStartPosition1 = x
                mWheelStartPosition2 = y
                val isExist = TimeUtil.isDateExists(a, b, dayString.toDouble().toInt())
                if (!isExist) {
                    mWheelStartPosition3 =
                        (mAllCusBeans?.get(mWheelStartPosition1)?.telSecondCategories?.get(
                            mWheelStartPosition2
                        )?.telThirdCategories?.size ?: 1) - 1
                } else {
                    mWheelStartPosition3 = z
                }
                val yearStart = mAllCusBeans?.get(mWheelStartPosition1)?.name ?: "2024"
                val monthStart = mAllCusBeans?.get(mWheelStartPosition1)?.telSecondCategories?.get(
                    mWheelStartPosition2
                )?.name ?: "12"
                val dayStart = mAllCusBeans?.get(mWheelStartPosition1)?.telSecondCategories?.get(
                    mWheelStartPosition2
                )?.telThirdCategories?.get(mWheelStartPosition3)?.name ?: "1"
                mStartTime = "${yearStart}-${monthStart}-${dayStart}"
                when (timeCurrent) {
                    0 -> {
                        wheelLinkageCus?.setDefaultValue(
                            mWheelStartPosition1,
                            mWheelStartPosition2,
                            mWheelStartPosition3
                        )
                        tvStart?.text = mStartTime
                        tvEnd?.text = mEndTime
                        tvStart?.setTextColor(Color.parseColor("#eb613d"))
                        viewStartLine?.setBackgroundResource(com.lv.common.R.drawable.bg_theme_2)
                        tvEnd?.setTextColor(Color.parseColor("#242424"))
                        viewEndLine?.setBackgroundResource(com.lv.common.R.drawable.bg_24_2)
                    }
                    1 -> {
                        wheelLinkageCus?.setDefaultValue(
                            mWheelEndPosition1,
                            mWheelEndPosition2,
                            mWheelEndPosition3
                        )
                        tvStart?.text = mStartTime
                        tvEnd?.text = mEndTime
                        tvStart?.setTextColor(Color.parseColor("#242424"))
                        viewStartLine?.setBackgroundResource(com.lv.common.R.drawable.bg_24_2)
                        tvEnd?.setTextColor(Color.parseColor("#eb613d"))
                        viewEndLine?.setBackgroundResource(com.lv.common.R.drawable.bg_theme_2)
                    }
                }
//                mPosition4Listener?.onClick(position, -1, -1, -1)
//                dismiss()
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun beforeDismiss() {
        super.beforeDismiss()

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.view_top, R.id.iv_close -> {
//                positionListener?.onClick(
//                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, data = null
//                )
                dismiss()
            }
            R.id.tv_title -> {
                mWheelPos = 0
                initUI(0)
            }
            R.id.tv_title_custom -> {
                mWheelPos = 1
                initUI(1)
                initStartScanTimePicker()
                initEndScanTimePicker()
            }
            R.id.tv_start -> {
                timeCurrent = 0
                initCustomTime()
            }
            R.id.tv_end -> {
                timeCurrent = 1
                initCustomTime()
            }

            R.id.tv_sure -> {
                if (mStartTime.isEmpty()) {
                    mStartTime = TimeUtil.getNowDateTime("yyyy-MM-dd")
                }
                if (mEndTime.isEmpty()) {
                    mEndTime = TimeUtil.getNowDateTime("yyyy-MM-dd")
                }
                val result = YgxUtilsKt.compareDates(mStartTime, mEndTime)
                when (result) {
                    1 -> {//第一个日期晚于第二个日期
                        val tempTime = mStartTime
                        mStartTime = mEndTime
                        mEndTime = tempTime
                        val po1 = mWheelStartPosition1
                        val po2 = mWheelStartPosition2
                        val po3 = mWheelStartPosition3
                        mWheelStartPosition1 = mWheelEndPosition1
                        mWheelStartPosition2 = mWheelEndPosition2
                        mWheelStartPosition3 = mWheelEndPosition3
                        mWheelEndPosition1 = po1
                        mWheelEndPosition2 = po2
                        mWheelEndPosition3 = po3
                    }
                    else -> {
                    }
                }
                positionListener?.onClick(
                    currentTopProvin,
                    mWheelPosition1,
                    mWheelPosition2,
                    mWheelPosition3,
                    mWheelStartPosition1,
                    mWheelStartPosition2,
                    mWheelStartPosition3,
                    mWheelEndPosition1,
                    mWheelEndPosition2,
                    mWheelEndPosition3,
                    mWheelPos ?: 0,
                    data = "${mStartTime}_$mEndTime"
                )
                dismiss()
            }
        }
    }


}